package io.gitee.zhucan123.core.config;

import com.niimbot.middlend.core.infrastructure.dataconversion.IntegerEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: zhuCan
 * @date: 17:29
 * @description: 数字 转枚举类
 */
public class EnumConverterFactory implements ConverterFactory<String, IntegerEnum> {

  private static final Map<Class, Converter> converterMap = new HashMap<>();

  @Override
  public <T extends IntegerEnum> Converter<String, T> getConverter(Class<T> aClass) {
    Converter<String, T> converter = converterMap.get(aClass);
    if (converter == null) {
      converter = new StringToEnumConverter<>(aClass);
      converterMap.put(aClass, converter);
    }
    return converter;
  }


}

class StringToEnumConverter<T extends IntegerEnum> implements Converter<String, T> {

  private Map<String, T> enumMap = new HashMap<>();

  StringToEnumConverter(Class<T> enumType) {
    T[] enums = enumType.getEnumConstants();
    for (T e : enums) {
      enumMap.put(e.getValue().toString(), e);
    }
  }

  @Override
  public T convert(String source) {

    T t = enumMap.get(source);
    if (t == null) {
      // 异常可以稍后去捕获
      throw new IllegalArgumentException("No element matches " + source);
    }
    return t;
  }
}
